package com.software.loginregister.util;
import android.util.JsonReader;
import java.io.IOException;
import java.io.StringReader;
public class SSEReader {
    public interface EventListener {
        void onEvent(String event, String data);

        void onError(String error);
    }

    public static void parseSSE(String line, EventListener listener) {
        if (line.startsWith("data: ")) {
            try {
                String jsonData = line.substring(6); // 去掉 "data: " 前缀
                JsonReader reader = new JsonReader(new StringReader(jsonData));
                reader.beginObject();

                String event = null;
                String thought = null;

                while (reader.hasNext()) {
                    String name = reader.nextName();
                    if (name.equals("event")) {
                        event = reader.nextString();
                    } else if (name.equals("thought")) {
                        thought = reader.nextString();
                    } else {
                        reader.skipValue();
                    }
                }

                reader.endObject();

                if (event != null && thought != null) {
                    listener.onEvent(event, thought);
                }
            } catch (IOException e) {
                listener.onError("解析SSE数据失败: " + e.getMessage());
            }
        }
    }
}